(function () {
  var domPageContainer = document.querySelector('.container');

  var slideSize = 3;
  var pageAreaSize = 2 * slideSize + 1;

  // 创建分页
  function createPage(curPage, totalPage) {
    domPageContainer.innerHTML = '';

    //创建首页
    var firstPage = document.createElement('a');
    firstPage.href = '';
    firstPage.innerHTML = '首页';
    if (curPage === 1) {
      firstPage.className = 'normal disabled';
    } else {
      firstPage.className = 'normal';
    }
    domPageContainer.appendChild(firstPage);
    firstPage.onclick = function (e) {
      e.preventDefault();
      createPage(1, totalPage);
    };
    //创建上一页
    var lastPage = document.createElement('a');
    lastPage.href = '';
    lastPage.innerHTML = '上一页';
    lastPage.className = 'normal';
    if (curPage === 1) {
      lastPage.className = 'normal disabled';
    } else {
      lastPage.className = 'normal';
    }
    domPageContainer.appendChild(lastPage);
    lastPage.onclick = function (e) {
      e.preventDefault();
      
      createPage(curPage - 1, totalPage);
    };

    //创建页码
    var min = 1,
      max = 1;
    if (pageAreaSize <= totalPage) {
      if (curPage <= slideSize) {
        min = 1;
        max = pageAreaSize;
      } else if (curPage >= totalPage - slideSize) {
        min = totalPage - pageAreaSize + 1;
        max = totalPage;
      } else {
        min = curPage - slideSize;
        max = curPage + slideSize;
      }
    } else {
      min = 1;
      max = totalPage;
    }

    for (var i = min; i <= max; i++) {
      var pageItem = document.createElement('a');
      pageItem.href = '';
      pageItem.innerHTML = i;
      if (i == curPage) {
        pageItem.className = 'active';
      } else {
        pageItem.className = 'normal';
      }
      domPageContainer.appendChild(pageItem);
    }

    //创建下页
    var nextPage = document.createElement('a');
    nextPage.href = '';
    nextPage.innerHTML = '下一页';

    if (curPage === totalPage) {
      nextPage.className = 'normal disabled';
    } else {
      nextPage.className = 'normal';
    }
    domPageContainer.appendChild(nextPage);
    nextPage.onclick = function (e) {
      e.preventDefault();
      createPage(curPage + 1, totalPage);
    };
    //创建尾页
    var endPage = document.createElement('a');
    endPage.href = '';
    endPage.innerHTML = '尾页';
    if (curPage === totalPage) {
      endPage.className = 'normal disabled';
    } else {
      endPage.className = 'normal';
    }
    domPageContainer.appendChild(endPage);
    endPage.onclick = function (e) {
      e.preventDefault();
      createPage(totalPage, totalPage);
    };
  }

  createPage(5, 6);
})();
